package com.ry.redis.utils;

import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {
	
    //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private static boolean test_on_borrow = true;
    
    private static JedisPool jedisPool = null;
    
    /**
     * 初始化Redis连接池
     */
	static {
		try {
			// 读取db.properties文件
			Properties props = new Properties();
			InputStream in = JedisUtil.class.getResourceAsStream("/redis.properties");
			// 加载文件
			props.load(in);
			// 读取信息
			String addr = props.getProperty("addr");
			int port = Integer.valueOf(props.getProperty("port"));
			String auth = props.getProperty("auth");
			int max_active = Integer.valueOf(props.getProperty("max_active"));
			int max_idle = Integer.valueOf(props.getProperty("max_idle"));
			int max_wait = Integer.valueOf(props.getProperty("max_wait"));
			int timeout = Integer.valueOf(props.getProperty("timeout"));

			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(max_active);
			config.setMaxIdle(max_idle);
			config.setMaxWaitMillis(max_wait);
			config.setTestOnBorrow(test_on_borrow);
			jedisPool = new JedisPool(config, addr, port, timeout, auth);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.close();
        }
    }
    
	public static void main(String[] args) {
		Jedis jedis = JedisUtil.getJedis();
		//设置 redis 字符串数据
        jedis.set("runoobkey", "www.baidu.com");
        // 获取存储的数据并输出
        System.out.println("redis 存储的字符串为: "+ jedis.get("runoobkey"));
		jedis.close();
	}
    
    
}
